from flask import Flask, render_template, request, redirect, url_for
from flask_login import LoginManager,\
    UserMixin, login_user, current_user, logout_user,login_required
from flask_wtf import FlaskForm
from wtforms import StringField
app = Flask(__name__)
app.secret_key = 'your_secret_key'

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'  # 设置您的登录页面的路由名称

# 模拟用户数据库
users = {'admin': {'password': 'admin123'}}

class User(UserMixin):
    pass

class MyForm(FlaskForm):
    username = StringField('账号')
    password = StringField('密码')

@login_manager.user_loader
def user_loader(username):
    if username not in users:
        return

    user = User()
    user.id = username
    return user

@app.route('/')
@login_required
def index():
    return '欢迎访问首页'

@app.route('/login', methods=['GET', 'POST'])
def login():
    form = MyForm()
    if form.validate_on_submit():
        username = request.form['username']
        password = request.form['password']

        if username in users and users[username]['password'] == password:
            user = User()
            user.id = username
            login_user(user)
            return redirect(url_for('index'))
        # return f'你好：{form.username.data} 密码:{form.password.data}'
    return render_template('login.html', form=form)

    # if request.method == 'POST':
    #
    #
    #     return '无效的用户名或密码'
    #
    # return render_template('login.html')

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        if username in users:
            return '用户名已存在'

        users[username] = {'password': password}
        return '注册成功'

    return render_template('register.html')

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('index'))



if __name__ == '__main__':
    app.run()